import { message } from 'antd';
import { PubSub } from 'pubsub-js';
import { history } from 'umi';
let websocket: WebSocket,
  lockReconnect = false;
let createWebSocket = (url: string) => {
  websocket = new WebSocket(url);
  console.log('ws connect')
  websocket.onopen = function () {
    console.log('ws open')
    message.success('连接成功')
    heartCheck.reset().start();
  };
  websocket.onerror = function () {
    message.error('连接失败，正常尝试重新连接')
    reconnect(url);
  };
  websocket.onclose = function (e) {
    heartCheck.reset()
    if (history.location.pathname.includes('/msg-detail')) {
      message.error('连接已断开')
      lockReconnect = false
      // 重新连接
      reconnect(url);
      return;
    }
    console.log('ws closed: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
  };
  websocket.onmessage = function (event) {
    lockReconnect = true;
    //event 为服务端传输的消息，在这里可以处理
    let data = JSON.parse(event.data);//把获取到的消息处理成字典，方便后期使用
    PubSub.publish('message', data); //发布接收到的消息 'message' 为发布消息的名称，data 为发布的消息

  };
};
let reconnect = (url: string) => {
  if (lockReconnect) return;
  // 没连接上会一直重连，设置延迟避免请求过多
  setTimeout(function () {
    message.warning('正在重新连接...')
    createWebSocket(url);
    lockReconnect = false;
  }, 4000);
};
let heartCheck = {
  timeout: 6000, // 6秒
  timeoutObj: null,
  reset: function () {
    // @ts-ignore
    clearInterval(this.timeoutObj);
    return this;
  },
  start: function () {
    // @ts-ignore
    this.timeoutObj = setTimeout(function () {
      if (websocket.readyState === 1) {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        // onmessage拿到返回的心跳就说明连接正常
        // websocket.send('HeartBeat');
        websocket.send(JSON.stringify({ type: 0 }))
        // 重置心跳检测
        heartCheck.reset().start()
      } else {
      }
    }, this.timeout);
  },
};
// 关闭连接
let closeWebSocket = () => {
  websocket && websocket.close();
};
export { heartCheck, websocket, createWebSocket, closeWebSocket };